package com.bridgetree.jubaocrm.ui.project;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;

/**
 * 添加报价
 */
public class XMChildAddBaoActivity extends Activity {
	private final String TAG = "XMChildAddBaoActivity";
	private Context mContext;
	private Projects mProjects;
	private EditText xm_bj_ed_date;
	private RelativeLayout xm_bj_RelativeLayout_select;
	private EditText xm_bj_ed_people;
	public static String peopleName = "";
	private InputMethodManager mInputMethodManager;
	private String user_id = "";
	private String token = "";

	@SuppressLint("SimpleDateFormat")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xmbj);
		mContext = this;

		peopleName = "";

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		mInputMethodManager = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, "");
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		EditText xm_bj_ed_allprice = (EditText) findViewById(R.id.xm_bj_ed_allprice);
		xm_bj_ed_allprice.setFocusable(true);   
		xm_bj_ed_allprice.setFocusableInTouchMode(true);   
		xm_bj_ed_allprice.requestFocus(); 
		
		xm_bj_ed_date = (EditText) findViewById(R.id.xm_bj_ed_date);
		TextView xm_bj_tv_title = (TextView) findViewById(R.id.xm_bj_tv_title);
		xm_bj_RelativeLayout_select = (RelativeLayout) findViewById(R.id.xm_bj_RelativeLayout_select);
		xm_bj_ed_people = (EditText) findViewById(R.id.xm_bj_ed_people);
		xm_bj_RelativeLayout_select = (RelativeLayout) findViewById(R.id.xm_bj_RelativeLayout_select);
		if (intent.getExtras() != null) {
			mProjects = (Projects) intent.getExtras().getSerializable(
					"my_projects");
			xm_bj_tv_title.setText("报价");
		}

		findViewById(R.id.xm_bj_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
					}
				});

		findViewById(R.id.xm_bj_bt_ok).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						getAddBao();
					}
				});
		xm_bj_RelativeLayout_select.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext,
						XMChildMemberListActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("baojia", "select");
				bundle.putSerializable("my_projects", mProjects);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String date = sDateFormat.format(new java.util.Date());
		xm_bj_ed_date.setText(date);
		xm_bj_ed_date.setOnTouchListener(new OnTouchListener() {// 设置点击的时候不弹出软键盘

					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						int inType = xm_bj_ed_date.getInputType(); // backup the
																	// input
																	// type
						xm_bj_ed_date.setInputType(InputType.TYPE_NULL); // disable
																			// soft
																			// input
						xm_bj_ed_date.onTouchEvent(event); // call native
															// handler
						xm_bj_ed_date.setInputType(inType); // restore input
															// type
						xm_bj_ed_date.setSelection(xm_bj_ed_date.getText()
								.length());
						return true;
					}
				});
		xm_bj_ed_date.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				selectDate();
			}
		});

	}

	String date;
	String time = "";
	Dialog Datedialog = null;
	Dialog Timedialog = null;

	private void selectDate() {
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker datePicker, int year, int month,
					int dayOfMonth) {
				date = year + "-" + (month + 1) + "-" + dayOfMonth;
				xm_bj_ed_date.setText(date);
			}
		};
		Datedialog = new DatePickerDialog(this, dateListener,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		Datedialog.show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (content != null && content.trim().equals("用户不存在")) {
							// finish();
						}
						if ("登陆失效，需重新登陆".equals(content)
								|| "join(f.username.errors)".equals(content)) {
							LoginUtil.executeLoginFaild(mContext);
						}

					}
				}).show();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!peopleName.equals("")) {
			xm_bj_ed_people.setText(peopleName);
		}
	}

	private void getAddBao() {
		EditText xm_bj_ed_allprice = (EditText) findViewById(R.id.xm_bj_ed_allprice);
		EditText xm_bj_ed_price = (EditText) findViewById(R.id.xm_bj_ed_price);
		EditText xm_bj_ed_zk = (EditText) findViewById(R.id.xm_bj_ed_zk);
		EditText xm_bj_ed_people = (EditText) findViewById(R.id.xm_bj_ed_people);
		String tip = "";
		String allprice = xm_bj_ed_allprice.getText().toString();
		if (allprice.equals("") || allprice.contains("-")
				|| allprice.contains("+") || allprice.contains(".")) {
			tip = "总价必须是整数\n";
		}
		String price = xm_bj_ed_price.getText().toString();
		if (price.equals("")) {
			tip += "请填写单价\n";
		} else if (price.length() < 2 || price.length() > 20) {
			tip += "单价必须是2-20个字符\n";
		}

		String zk = xm_bj_ed_zk.getText().toString();
		if (zk.equals("")) {
			tip += "请输入折扣\n";
		} else if (zk.contains("-") || zk.contains("+") || zk.contains(".")) {
			tip += "折扣必须是整数\n";
		} else {
			try {
				int iv = Integer.valueOf(zk);
				if (iv > 0 && iv < 100) {
				} else {
					tip += "折扣只能是1-100之间的数字 \n";
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				tip += "折扣只能是1-100之间的数字 \n";
			}
		}
		String people = xm_bj_ed_people.getText().toString();
		if (people.equals("")) {
			tip += "请选择报价人";
		} else if (people.length() < 2 || people.length() > 50) {
			tip += "报价人必须是2-50个字符\n";
		}

		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (allprice.equals("") || allprice.contains("-")
				|| allprice.contains("+") || allprice.contains(".")
				|| price.equals("") || price.length() < 2
				|| price.length() > 20 || zk.equals("") || zk.contains("-")
				|| zk.contains("+") || zk.contains(".") || people.equals("")
				|| people.length() < 2 || people.length() > 50) {
			openDailog("错误提示", tip);
		} else if (tip.contains("折扣只能是1-100之间的数字")) {
			openDailog("错误提示", tip);
		} else {
			final ProgressDialog progressDialog = ProgressDialogUtil
					.show(mContext);
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("project_id", mProjects.getProject_id());
			mMap.put("current_price", xm_bj_ed_allprice.getText().toString());
			mMap.put("one_price", xm_bj_ed_price.getText().toString());
			mMap.put("discount", xm_bj_ed_zk.getText().toString());
			mMap.put("quote_people", xm_bj_ed_people.getText().toString());
			mMap.put("quote_date", xm_bj_ed_date.getText().toString());
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN + "/quote";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println(response.toString());
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														// openDailog("失败提示",
														// desc);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

}